﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WXYW.Model;
using WXYW.BLL;
using WXYW.DAL;
using System.Collections;

namespace WXYW
{
    public partial class ManageSparePartPlatform : System.Web.UI.Page
    {
        public int RecordsNumber { get; set; }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindSparePartList();
            }
        }

        private void BindSparePartList()
        {
            SparePartService sparePartService = new SparePartService();

            List<SparePartModel> models = new List<SparePartModel>();

            if (ContextService.CurrentAccount.UserType.ID == (int)RoleType.Administrator)
            {
                models = sparePartService.GetAllSparePartModel(keyWordTextBox.Text);
            }
            else
            {
                models = sparePartService.GetSparePartModelByPlatform(keyWordTextBox.Text, ContextService.CurrentAccount.ServiceStation.ID);
            }

            RecordsNumber = models.Count;
            SparePartListGridView.DataSource = models;
            SparePartListGridView.DataBind();
        }

        protected void SparePartListGridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            SparePartService sparePartService = null;
            SparePart sparePartEntity = null;
            switch (e.CommandName)
            {
                case "Look":
                    Response.Redirect(string.Format("SparePartRecord.aspx?ID={0}", e.CommandArgument));
                    break;
                case "Transfer":
                    sparePartService = new SparePartService();
                    sparePartEntity = sparePartService.GetSparePartEntityByID(Convert.ToInt32(e.CommandArgument));
                    modelNOTxtBox.Text = sparePartEntity.ModelNumber;
                    versionNOTxtBox.Text = sparePartEntity.VersionNumber;
                    storageCountTxtBox.Text = sparePartEntity.Count.HasValue ? sparePartEntity.Count.Value.ToString() : "0";

                    HiddenField.Value = e.CommandArgument.ToString();
                    ResetTransferPanel();
                    transferPopupExtender.Show();
                    break;
                case "Lend":
                    sparePartService = new SparePartService();
                    sparePartEntity = sparePartService.GetSparePartEntityByID(Convert.ToInt32(e.CommandArgument));
                    lendModelNOTxtBox.Text = sparePartEntity.ModelNumber;
                    lendVersionNOTxtBox.Text = sparePartEntity.VersionNumber;
                    lendStorageCountTxtBox.Text = sparePartEntity.Count.ToString();
                    lendDateTextBox.Text = DateTime.Now.ToShortDateString();
                    HiddenField.Value = e.CommandArgument.ToString();
                    saveLendButton.Enabled = false;
                    sendBtn.Enabled = true;
                    ResetLendPanel();

                    warningInfo.Text = "";
                    LendPopupExtender.Show();
                    break;
                case "PlatformLend":
                    sparePartService = new SparePartService();
                    sparePartEntity = sparePartService.GetSparePartEntityByID(Convert.ToInt32(e.CommandArgument));
                    platformlendModelNOTxtBox.Text = sparePartEntity.ModelNumber;
                    platformlendVersionNOTxtBox.Text = sparePartEntity.VersionNumber;
                    platformlendStorageCountTxtBox.Text = sparePartEntity.Count.ToString();
                    platformlendDateTextBox.Text = DateTime.Now.ToShortDateString();
                    HiddenField.Value = e.CommandArgument.ToString();

                    ServiceStationService serviceStationService = new ServiceStationService();
                    IQueryable<ServiceStation> serviceStationList = serviceStationService.GetALLServiceStations();
                    serviceStationDDL.DataSource = serviceStationList;
                    serviceStationDDL.DataTextField = "Name";
                    serviceStationDDL.DataValueField = "ID";
                    serviceStationDDL.DataBind();

                    platformLendWarnInfo.Text = "";
                    ResetPlatformLendPanel();
                    PlatformLendPopupExtender.Show();
                    break;
            }
        }

        private void ResetTransferPanel()
        {
            transferCountTextBox.Text = string.Empty;
        }

        private void ResetLendPanel()
        {
            lendCountTxtBox.Text = string.Empty;
            lendMessageLbl.Text = string.Empty;
            lendReasonTextBox.Text = string.Empty;
            customerNameTxtBox.Text = string.Empty;
            contactPersonTextBox.Text = string.Empty;
            contactPhoneTextBox.Text = string.Empty;
            addressTextBox.Text = string.Empty;
            emailTextBox.Text = string.Empty;
            lendDeadlineTextBox.Text = string.Empty;
            saveLendButton.Enabled = false;
            lendMessageLbl.Text = "请先填写相关信息，然后点击发送。";
        }

        private void ResetPlatformLendPanel()
        {
            platformLendDeadlineDateTxtBox.Text = string.Empty;
            platformLendReason.Text = string.Empty;
            platformLendCountTxtBox.Text = string.Empty;
        }

        protected void TransferPanel_Load(object sender, EventArgs e)
        {
            managerLbl.Text = ContextService.CurrentAccount.UserName;
        }

        protected void saveBtn_Click(object sender, EventArgs e)
        {
            try
            {
                SparePartService sparePartService = new SparePartService();
                sparePartService.TransferSparePartInPlatform(transferTypeDropdownList.SelectedValue, Convert.ToInt32(HiddenField.Value),
                    Convert.ToInt32(transferCountTextBox.Text), commentTxtBox.Text, ContextService.CurrentAccount);

                messageLbl.Text = "操作成功";
                BindSparePartList();
            }
            catch (Exception ex)
            {
                messageLbl.Text = string.Format("操作失败：{0}", ex.Message);
            }
        }

        protected void sendBtn_Click(object sender, EventArgs e)
        {
            SparePartService sparePartService = new SparePartService();
            SparePart sparePartEntity = sparePartService.GetSparePartEntityByID(Convert.ToInt32(HiddenField.Value));

            if (Convert.ToInt32(lendCountTxtBox.Text) > sparePartEntity.Count)
            {
                warningInfo.Text = "数量输入有误！";
                LendPopupExtender.Show();
                return;
            }
            LendPersonLbl.Text = contactPersonTextBox.Text;
            sendEmailTxtBox.Text = emailTextBox.Text;

            emailBodyTxtBox.Text = string.Format("{0}, 您好：您借用的产品型号为{1}，版本号为{2}，数量为 {3}的产品今天提供给您了，借用日期{4}， 您使用截止日期{5}， 请务必于截止日期{5}内归还，谢谢。",
                LendPersonLbl.Text, sparePartEntity.ModelNumber, sparePartEntity.VersionNumber, lendCountTxtBox.Text, DateTime.Now.ToShortDateString(), lendDeadlineTextBox.Text);

            LendNoticePopupExtender.Show();
        }

        protected void saveLendButton_Click(object sender, EventArgs e)
        {
            try
            {
                SparePartService sparePartService = new SparePartService();
                sparePartService.SaveLendRecord(Convert.ToInt32(HiddenField.Value), Convert.ToInt32(lendCountTxtBox.Text), customerNameTxtBox.Text,
                    contactPersonTextBox.Text, contactPhoneTextBox.Text, emailTextBox.Text, addressTextBox.Text, Convert.ToDateTime(lendDeadlineTextBox.Text),
                    ContextService.CurrentAccount, lendReasonTextBox.Text);

                lendMessageLbl.Text = "记录日志已保存, 请点击关闭。";
                saveLendButton.Enabled = false;
                LendNoticePopupExtender.Hide();

                BindSparePartList();
            }
            catch (Exception ex)
            {
                lendMessageLbl.Text = "保存错误，请联系管理员。";
            }
        }

        protected void savePlatformLendBtn_Click(object sender, EventArgs e)
        {
            try
            {
                SparePartService sparePartService = new SparePartService();
                sparePartService.SavePlatformLendRecord(Convert.ToInt32(HiddenField.Value), Convert.ToInt32(platformLendCountTxtBox.Text),
                    Convert.ToInt32(serviceStationDDL.SelectedValue), Convert.ToDateTime(platformLendDeadlineDateTxtBox.Text),
                    ContextService.CurrentAccount, platformLendReason.Text);

    
                SparePart sparePartEntity = sparePartService.GetSparePartEntityByID(Convert.ToInt32(HiddenField.Value));

                string noticeEmailString = string.Format("{0}, 您好：您的平台借用的产品型号为{1}，版本号为{2}，数量为 {3}的产品今天提供给您了，借用日期{4}， 您使用截止日期{5}， 请务必于截止日期{5}内归还，谢谢。",
                LendPersonLbl.Text, sparePartEntity.ModelNumber, sparePartEntity.VersionNumber, lendCountTxtBox.Text, DateTime.Now.ToShortDateString(), lendDeadlineTextBox.Text);

                ServiceStationService serviceStationService = new ServiceStationService();
                ServiceStation serviceStation = serviceStationService.GetServiceStation(Convert.ToInt32(serviceStationDDL.SelectedValue));
                EmailService.SendEmail(serviceStation.EMail, "备件借用通知", noticeEmailString);
                BindSparePartList();

                platformLendWarnInfo.Text = "备件借用记录保存成功，请点击关闭按钮关闭当前窗口。";
            }
            catch (Exception ex)
            {
                platformLendWarnInfo.Text = "保存错误，请联系管理员。";
            }
        }

        protected void sendEmailButton_Click(object sender, EventArgs e)
        {
            EmailService.SendEmail(sendEmailTxtBox.Text, "备件借用通知", emailBodyTxtBox.Text);
            LendNoticePopupExtender.Hide();
            sendBtn.Enabled = false;
            saveLendButton.Enabled = true;
            lendMessageLbl.Text = "邮件通知已发送，请点击保存。";
            warningInfo.Text = "";
            LendPopupExtender.Show();
        }

        protected void SparePartListGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.DataItem != null)
            {
                e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#FFFF99'");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
            }

            if (e.Row.RowType == DataControlRowType.Pager)
            {
                DropDownList pageDDL = e.Row.FindControl("pageDDL") as DropDownList;
                for (int index = 1; index <= SparePartListGridView.PageCount; index++)
                {
                    pageDDL.Items.Add(index.ToString());
                }
                pageDDL.SelectedValue = (SparePartListGridView.PageIndex + 1).ToString();
            }
        }

        protected IEnumerable GridView_MustAddARow(IEnumerable data)
        {
            List<SparePartModel> dds = new List<SparePartModel>();
            dds.Add(new SparePartModel());
            return dds;
        }

        protected void pageDDL_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList pageDDL = sender as DropDownList;
            SparePartListGridView.PageIndex = Convert.ToInt32(pageDDL.SelectedIndex);
            BindSparePartList();
        }

        protected void sparePartApplyFormsGridView_DataBound(object sender, EventArgs e)
        {
            if (SparePartListGridView.BottomPagerRow != null)
            {
                SparePartListGridView.BottomPagerRow.Visible = true;
            }
        }

        protected void searchLinkButton_Click(object sender, EventArgs e)
        {
            BindSparePartList();
        }

        protected void resetLinkButton_Click(object sender, EventArgs e)
        {
            keyWordTextBox.Text = "";
            BindSparePartList();
        }

        protected void SparePartListGridView_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {

        }

        protected void SparePartListGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            SparePartListGridView.PageIndex = e.NewPageIndex;
        }
    }
}
